<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">

  <!-- CSRF -->
  <meta name="_csrf" th:content="${_csrf.token}"/>
  <!-- default header name is X-CSRF-TOKEN -->
  <meta name="_csrf_header" th:content="${_csrf.headerName}"/>

  <title>Update Password</title>
</head>
<body>
<p>Old Password: <input name="oldPassword" id="oldPassword" type="password"/></p>
<p>New Password: <input name="newPassword" id="newPassword" type="password"/></p>
<p>
  <button type="submit" id="submit">OK</button>
</p>
</body>
<script>
  const csrf = document.getElementsByName('_csrf')[0].getAttribute('content');
  const csrfHeader = document.getElementsByName('_csrf_header')[0].getAttribute('content');

  document.getElementById('submit').addEventListener('click', () => {
    const oldPassword = document.getElementById('oldPassword').value;
    const newPassword = document.getElementById('newPassword').value;

    let error = '';
    if (!oldPassword) error = 'Old password cant be empty.';
    else if (!newPassword) error = 'New password cant be empty.';

    if (error) {
      alert(error);
      return;
    }

    fetch('/api/account/updatePassword', {
      method: 'post',
      headers: {
        [csrfHeader]: csrf,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({oldPassword, newPassword}),
    }).then(res => res.json()).then(res => {
      if (res.message) {
        alert(res.message);

        if (res.code === 0) location.href = '/';
      }
    });
  }, !1);
</script>
</html>
